package com.loma.utils;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import java.io.IOException;
import java.util.Map;

/**
 * Created by loma on 2017/3/14.
 */
public class JsonUtil {

    public static Map<String, Object> jsonToMap(String json) {

        ObjectMapper objectMapper = new ObjectMapper();
        Map<String, Object> maps = null;
        try {
            maps = objectMapper.readValue(json, Map.class);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return maps;
    }

    public static String toJson(Object obj) {

        ObjectMapper objectMapper = new ObjectMapper();
        String json = null;
        try {
            objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
                    .disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES);
            json = objectMapper.writeValueAsString(obj);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }

    public static <T> T fromJson(String jsonStr, Class<T> cls) {
        ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES)
                .disable(DeserializationFeature.FAIL_ON_NULL_FOR_PRIMITIVES);
        try {

            return objectMapper.readValue(
                    jsonStr, cls);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }

    }
}
